package com.centriole.service.workflow.service.impl;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Comment;

import java.util.List;

/**
 * 功    能：流程跳转
 * 创建人：王鑫
 * 时    间：2018年1月5日下午3:18:15
 */
public class TaskCommitCmd implements Command<Comment> {
    protected String instanceId;
    protected String nodeId;

    public TaskCommitCmd(String instanceId,String nodeId) {
        this.instanceId = instanceId;
        this.nodeId=nodeId;
    }
    public Comment execute(CommandContext commandContext) {
        TaskEntityManager taskEntityManager = Context.getCommandContext().getTaskEntityManager();
        ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();

        ExecutionEntity executionEntity = executionEntityManager.findExecutionById(instanceId);
        List<TaskEntity> taskEntityList = taskEntityManager.findTasksByProcessInstanceId(instanceId);
        for (TaskEntity taskEntity : taskEntityList) {
            taskEntityManager.deleteTask(taskEntity, "cancel", false);
            taskEntity.getExecution().removeTask(taskEntity);
            //主干任务时，Execution等同于ProcessInstance，ID也相同
            //分子任务时，需要删除Execution，不然会影响下面的分子任务执行
            if (!taskEntity.getExecution().getId().equals(instanceId))
                taskEntity.getExecution().remove();
        }
        ActivityImpl activity = null;
        if (nodeId!=null) {
//            ActivityImpl currentActivity = executionEntity.getProcessDefinition().findActivity(nodeId);
//            String sourceCode = currentActivity.getIncomingTransitions().get(0).getSource().getId();
            activity = executionEntity.getProcessDefinition().findActivity(nodeId);
        }
        executionEntity.executeActivity(activity);
        return null;
    }
}
